/*
 * @Author: lijing
 * @e-mail: 1413979079@qq.com
 * @LastEditors: lijing
 * @Date: 2019-10-10 18:16:41
 * @LastEditTime: 2020-04-26 23:00:06
 * @FilePath: \blog-pages\src\request\http.js
 * @Description: 请求实例
 */

import axios from 'axios'
import router from '@/router/index'
import store from '@/store'
import Vue from '@/main.js'
import url from './url'

// 设置请求超时时间,并创建axios实例
var instance = axios.create({
  baseURL: url.baseUrl,
  timeout: 1000 * 10,
  headers: { 'Content-Type': 'application/json;charset=UTF-8' },
});

// 请求拦截
instance.interceptors.request.use(
  config => {
    if (config.url.startsWith("admin")) {
      let token = store.state.app.adminToken;
      // console.log('config admin_token : ' + token)
      token && (config.headers.Authorization = token);
    } else {
      const userInfo = store.state.user.userInfo;
      userInfo && (config.headers.Authorization = userInfo.token);
    }
    return config;
  },
  error => {
    return Promise.error(error);
  }
);

// 响应拦截
instance.interceptors.response.use(
  response => {
    // 如果返回的状态码为200，说明接口请求成功，可以正常拿到数据
    // 否则的话抛出错误
    if (response.status === 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  error => {
    // console.log(error)
    const res = error.response;
    if (res) {
      // 状态码判断
      switch (res.status) {
        // 403为token过期
        case 403:
          // 弹出重新登录的提示
          Vue.$bvToast.toast("登录已过期，请重新登录哦", {
            title: "提示",
            variant: "danger",
            solid: true,
            toaster: "b-toaster-top-center"
          });
          break;
        // 404请求不存在
        case 404:
          router.push("/error404");
          break;
        default:
          router.push("/error500");
      }
    } else {
      router.push("/error500");
    }
    return Promise.reject(error);
  }
);

export default instance;
